<template>
  <!-- 新增和修改抽屉 -->
  <el-dialog
    @close="cancel"
    :title="title"
    :visible.sync="drawer"
    width="70%"
    class="dialogClass"
    append-to-body
  >
    <template slot="title">
      <div class="modalTitle">
        <img
          src="@/assets/bluelogo/drawerTitle.png"
          alt=""
          class="titleLogo"
        />{{ title }}
      </div>
    </template>
    <!-- <template slot="title">
      <div class="drawerTitle">
        <img
          src="../../../../assets/bluelogo/drawerTitle.png"
          alt=""
          class="titleLogo"
        />{{ title }}
      </div>
    </template> -->
    <!-- 任务基本信息 -->
    <el-form :rules="rules" ref="form" :model="formData" label-width="80px">
      <div class="descriptionsContainer1">
        <div class="pageHeader">任务基本信息</div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="任务名称" prop="taskName">
              <el-input
                class="taskName"
                maxlength="200"
                v-model="formData.taskName"
                placeholder="请输入任务名称"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属案件" prop="caseId">
              <el-select
                :disabled="type == 'edit'"
                class="taskName"
                v-model="formData.caseId"
                placeholder="请选择所属案件"
              >
                <el-option
                  v-for="item in cases"
                  :key="item.id"
                  :label="item.caseName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="案件类型" prop="taskType">
              <el-select
                class="taskName"
                v-model="formData.taskType"
                placeholder="请选择案件类型"
                :disabled="type == 'edit'"
              >
                <el-option
                  v-for="dict in dict.type.case_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <el-divider></el-divider>
      <!-- 涉案人信息 -->
      <div class="descriptionsContainer1">
        <div class="pageHeader">涉案人信息</div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名" prop="involvedPersonVO.name">
              <el-input
                class="taskName"
                v-model="formData.involvedPersonVO.name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="involvedPersonVO.zjh">
              <el-input
                class="taskName"
                v-model="formData.involvedPersonVO.zjh"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="involvedPersonVO.tel">
              <el-input
                class="taskName"
                v-model="formData.involvedPersonVO.tel"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="户籍地址"
              prop="involvedPersonVO.residenceAddress"
            >
              <el-input
                class="taskName"
                v-model="formData.involvedPersonVO.residenceAddress"
                placeholder="请输入"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item
              label="居住地址"
              :required="true"
              :show-message="false"
            >
              <el-row :gutter="24" class="oucodeList">
                <el-col :span="7">
                  <el-form-item
                    label-width="0"
                    label=""
                    prop="involvedPersonVO.oucodeList[0]"
                  >
                    <DictionarySelect
                      placeholder="请选择省"
                      source="xzqhbm"
                      v-model="formData.involvedPersonVO.oucodeList[0]"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label-width="0"
                    label=""
                    prop="involvedPersonVO.oucodeList[1]"
                  >
                    <DictionarySelect
                      placeholder="请选择市"
                      :source="formData.involvedPersonVO.oucodeList[0]"
                      v-model="formData.involvedPersonVO.oucodeList[1]"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    label-width="0"
                    label=""
                    prop="involvedPersonVO.oucodeList[2]"
                  >
                    <DictionarySelect
                      placeholder="请选择区县"
                      :source="formData.involvedPersonVO.oucodeList[1]"
                      v-model="formData.involvedPersonVO.oucodeList[2]"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="具体地址" prop="involvedPersonVO.liveAddress">
              <el-input
                class="taskName1"
                v-model="formData.involvedPersonVO.liveAddress"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <el-divider></el-divider>
    <!-- 待核查信息 -->
    <div class="descriptionsContainer1">
      <div class="pageHeader">
        待核查信息<el-tooltip
          class="item"
          effect="dark"
          content="点击添加待核查信息"
          placement="top-start"
        >
          <i
            class="iconClass el-icon-circle-plus"
            @click="addUncheckedInfor"
          ></i>
        </el-tooltip>
      </div>
      <el-form
        ref="uncheckedInfor"
        :rules="uncheckedInforRules"
        v-for="(unCheck, index) in uncheckedInformation"
        :key="index"
        :model="uncheckedInformation[index]"
        label-width="110px"
      >
        <div class="uncheckedInfor">
          <el-row>
            <el-col :span="6">
              <el-form-item label="投资金额(元)" prop="investmentMoney">
                <el-input
                  :maxlength="15"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  :disabled="!(unCheck.edit || unCheck.add)"
                  class="taskName1"
                  v-model="uncheckedInformation[index].investmentMoney"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="提取金额(元)" prop="withdrawalMoney">
                <el-input
                  :maxlength="15"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  :disabled="!(unCheck.edit || unCheck.add)"
                  class="taskName1"
                  v-model="uncheckedInformation[index].withdrawalMoney"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="损失金额(元)" prop="lossMoney">
                <el-input
                  :maxlength="15"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  :disabled="!(unCheck.edit || unCheck.add)"
                  class="taskName1"
                  v-model="uncheckedInformation[index].lossMoney"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="时间" prop="time">
                <el-date-picker
                  class="taskName1"
                  :disabled="!(unCheck.edit || unCheck.add)"
                  v-model="uncheckedInformation[index].time"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期时间"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户银行">
                <el-input
                  :maxlength="50"
                  :disabled="!(unCheck.edit || unCheck.add)"
                  class="taskName1"
                  v-model="uncheckedInformation[index].accountBank"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="开户名称">
                <el-input
                  :maxlength="50"
                  :disabled="!(unCheck.edit || unCheck.add)"
                  class="taskName1"
                  v-model="uncheckedInformation[index].accountName"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="开户账号">
                <el-input
                  :maxlength="50"
                  :disabled="!(unCheck.edit || unCheck.add)"
                  class="taskName1"
                  v-model="uncheckedInformation[index].accountNum"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-button
            class="searchButton1"
            v-if="unCheck.add || unCheck.edit"
            @click="handleSubmit(index)"
            >确定
          </el-button>
          <el-button
            class="searchButton1"
            v-if="!(unCheck.add || unCheck.edit)"
            @click="handleEdit(index)"
            >编辑
          </el-button>
          <el-button class="resetButton1" @click="handleDeleteUnchecked(index)"
            >删除
          </el-button>
        </div>
        <div class="pageHeaderSub">
          <span class="title">*相关附件</span>
          <uploadAttachments
            :uncheckedInformationindex="index"
            ref="uploadAttachments"
            @uploadDisplay="uploadDisplay"
          ></uploadAttachments>

          <span class="pageleft">支持扩展名：{{ picTypeList }}</span>
          <el-button
            class="searchButton1"
            @click="allpicDownload(unCheck.taskAccessoryList)"
            >下载</el-button
          >
        </div>

        <div class="enclosuresBox">
          <div
            class="enclosures2"
            v-for="(item, index) in unCheck.taskAccessoryList"
            :key="index"
          >
            <div class="enclosurebtn2">
              <el-image
                v-if="item.picUrl"
                fit="cover"
                class="picPreview"
                :src="item.picUrl"
              />
              <div class="enclosurebtn3">
                <div class="enclosurebtn4">
                  <img
                    class="enclosureDel3"
                    @click="handleDownload(item)"
                    src="@/assets/images/downloadIcon.png"
                  />
                  <img
                    @click="handlePreview(item)"
                    class="enclosureDel3"
                    src="@/assets/images/viewIcon.png"
                  />
                  <img
                    @click="handleDelFile(item, unCheck, index)"
                    class="enclosureDel3"
                    src="@/assets/images/delIcon.png"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-divider
          v-if="index !== uncheckedInformation.length - 1"
        ></el-divider>
      </el-form>
    </div>
    <div slot="footer">
      <div class="dialog-footer">
        <el-button class="resetButton" @click="cancel">取消</el-button>
        <el-button class="searchButton" @click="submit">确定</el-button>
      </div>
    </div>
    <picPreview ref="picPreview" :picUrl="picUrl"></picPreview>

    <!-- </el-drawer> -->
  </el-dialog>
</template>

<script>
import { MODALTYPE, FILETYPE, ZJH, TEL } from "../../../../utils/variable";
import uploadAttachments from "./uploadAttachments.vue";
import picPreview from "./picPreview.vue";
import DictionarySelect from "@/components/DictionarySelect/DictionarySelect.vue";
import {
  getCaseList,
  addCheckTask,
  updateCheckTask,
  getCheckTask,
  onlinePreview,
  downloadFile,
} from "@/api/checkTask/task";
export default {
  dicts: ["case_type"],
  name: "taskDrawer",
  components: { uploadAttachments, picPreview, DictionarySelect },
  data() {
    return {
      picTypeList: "",
      picUrl: "",
      //抽屉是否显示
      drawer: false,
      title: "",
      // 待核查信息
      uncheckedInformation: [],
      uncheckedInformationindex: 1,

      cases: [],
      formData: {
        // 任务名称
        taskName: "",
        // 案件id
        caseId: "",
        // 任务类型
        taskType: "",
        involvedPersonVO: {
          name: "",
          zjh: "",
          oucodeList: ["", "", ""],
          residenceAddress: "",
          liveAddress: "",
          tel: "",
        },
      },
      queryParam: {
        caseId: "",
        oucode: "",
      },
      invaildInfo: "",
      telinvaildInfo: "",
      rules: {
        taskName: [
          {
            required: true,
            message: "请输入任务名称",
            trigger: "blur",
          },
        ],
        caseId: [
          {
            required: true,
            message: "请选择所属案件",
            trigger: "change",
          },
        ],
        taskType: [
          {
            required: true,
            message: "请选择案件类型",
            trigger: "change",
          },
        ],
        "involvedPersonVO.name": [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur",
          },
        ],
        "involvedPersonVO.zjh": [
          {
            required: true,
            message: "请输入身份证号",
            trigger: "blur",
          },
          {
            pattern: ZJH,
            message: "身份证号格式错误",
            trigger: "blur",
          },
        ],
        "involvedPersonVO.oucodeList[0]": [
          {
            required: true,
            message: "请选择所属省",
            trigger: "change",
          },
        ],
        "involvedPersonVO.oucodeList[1]": [
          {
            required: true,
            message: "请选择所属市",
            trigger: "change",
          },
        ],
        "involvedPersonVO.oucodeList[2]": [
          {
            required: true,
            message: "请选择所属区县",
            trigger: "change",
          },
        ],
        // "involvedPersonVO.residenceAddress": [
        //   {
        //     required: true,
        //     message: "请输入户籍地址",
        //     trigger: "blur",
        //   },
        // ],
        "involvedPersonVO.liveAddress": [
          {
            required: true,
            message: "请输入具体地址",
            trigger: "blur",
          },
        ],
        "involvedPersonVO.tel": [
          {
            required: true,
            message: "请输入联系电话",
            trigger: "blur",
          },
          {
            pattern: TEL,
            message: "手机号格式错误",
            trigger: "blur",
          },
        ],
      },
      uncheckedInforRules: {
        investmentMoney: [
          {
            required: true,
            message: "请输入投资金额",
            trigger: "blur",
          },
        ],
        withdrawalMoney: [
          {
            required: true,
            message: "请输入提取金额",
            trigger: "blur",
          },
        ],
        lossMoney: [
          {
            required: true,
            message: "请选择损失金额",
            trigger: "blur",
          },
        ],
        time: [
          {
            required: true,
            message: "请选择时间",
            trigger: "change",
          },
        ],
      },
    };
  },
  props: ["type", "id", "caseId", "oucode"],
  created() {
    let labelList = [];
    this.getDicts("pic_type").then((response) => {
      response.data.forEach((el) => {
        labelList.push(el.dictLabel);
      });
      this.picTypeList = labelList.join();
    });
  },
  methods: {
    // 上传附件
    uploadDisplay(value, index) {
      let fileType = value.data.name.split(".");
      let file = {
        name: value.data.name,
        url: value.data.url,
        fileType: fileType[fileType.length - 1],
        accessorySource: FILETYPE.unCheckEnclosure,
      };
      let queryParam = {
        filename: file.url,
      };
      downloadFile(queryParam).then((res) => {
        let blob = new Blob([res]); // 返回的文件流数据
        let picurl = window.URL.createObjectURL(blob); // 将他转化为路径
        file.picUrl = picurl;
        this.uncheckedInformation[index].taskAccessoryList.push(file);
      });
    },
    // 表单重置
    reset() {
      this.uncheckedInformation = [];
      this.resetForm("form");
      this.formData.involvedPersonVO.oucodeList = ["", "", ""];
    },
    // 图片一键下载
    allpicDownload(item) {
      if (item.length == 0) {
        this.$message({
          message: "当前相关附件为空",
          type: "warning",
        });
      } else {
        for (let i = 0; i < item.length; i++) {
          this.handleDownload(item[i]);
        }
      }
    },
    // 附件下载
    handleDownload(item) {
      this.download(
        "/file/downloadFileNew",
        {
          filename: item.url,
        },
        item.url
      );
    },
    // 附件预览
    handlePreview(item) {
      let queryParam = {
        filename: item.url,
      };
      downloadFile(queryParam).then((res) => {
        let blob = new Blob([res]); // 返回的文件流数据
        let url = window.URL.createObjectURL(blob); // 将他转化为路径
        this.picUrl = url; // 将转换出来的路径赋值给变量，其实和上一步结合就可以
        this.$refs.picPreview.open = true;
      });
    },
    // 附件删除
    handleDelFile(row, unCheck, unCheckindex) {
      console.log(row, unCheck, unCheckindex);
      this.$modal
        .confirm("是否确认删除该附件？")
        .then(() => {
          unCheck.taskAccessoryList.splice(unCheckindex, 1);
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    //取消
    cancel() {
      this.$emit("update:type", "");
      this.reset();
      this.drawer = false;
    },
    //提交
    submit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let submitFlag = false;
          this.uncheckedInformation.forEach((el) => {
            if (el.isSave == false) {
              submitFlag = true;
            }
          });
          if (submitFlag == true) {
            this.$message.warning(
              "当前表单存在未保存核查任务信息，请确认后再提交！"
            );
          } else {
            if (this.type == MODALTYPE["修改"]) {
              this.formData.uncheckInfoList = this.uncheckedInformation;
              updateCheckTask(this.formData).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.reset();
                this.drawer = false;
                this.$emit("update:type", "");
                this.$emit("fatherMethod");
              });
            } else if (this.type == MODALTYPE["新增"]) {
              this.formData.uncheckInfoList = this.uncheckedInformation;
              addCheckTask(this.formData).then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.reset();
                this.drawer = false;
                this.$emit("update:type", "");
                this.$emit("fatherMethod");
              });
            }
          }
        }
      });
    },
    // 获取所属案件
    getAllCaseList() {
      this.queryParam.caseId = this.caseId;
      this.queryParam.oucode = this.oucode;
      getCaseList(this.queryParam).then((response) => {
        this.cases = response.data;
      });
    },
    //待核查信息删除
    handleDeleteUnchecked(row) {
      this.$modal
        .confirm("是否确认删除该条待核查信息？")
        .then(() => {
          this.uncheckedInformation.forEach((element, index) => {
            if (index == row) {
              this.uncheckedInformation.splice(index, 1);
            }
          });

          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    //待核查信息确认
    handleSubmit(index) {
      this.$refs["uncheckedInfor"][index].validate((valid) => {
        if (valid) {
          this.$set(this.uncheckedInformation[index], "edit", false);
          this.$set(this.uncheckedInformation[index], "add", false);
          this.$set(this.uncheckedInformation[index], "isSave", true);
        }
      });
    },

    //待核查信息编辑
    handleEdit(index) {
      const isediting = this.uncheckedInformation.some((r) => r.edit);
      if (isediting) {
        this.$message({
          message: "同时只能有一个编辑行",
          type: "warning",
        });
      } else {
        this.$set(this.uncheckedInformation[index], "edit", true);
        this.$set(this.uncheckedInformation[index], "isSave", false);
      }
    },
    // 新增待核查信息
    addUncheckedInfor() {
      const isAdding = this.uncheckedInformation.some((r) => r.add);
      if (isAdding) {
        this.$message({
          message: "只能有一个新增行",
          type: "warning",
        });
      } else {
        this.uncheckedInformation.push({
          isSave: false,
          add: true,
          investmentMoney: "",
          withdrawalMoney: "",
          lossMoney: "",
          time: "",
          accountBank: "",
          accountName: "",
          accountNum: "",
          taskAccessoryList: [],
        });
      }
    },
  },

  watch: {
    type(val) {
      if (this.type == MODALTYPE["新增"]) {
        this.reset();
        this.getAllCaseList();
        this.title = "核查任务新增";
        this.drawer = true;
      } else if (this.type == MODALTYPE["修改"]) {
        this.reset();
        this.title = "核查任务修改";
        // 请求后端拿到数据
        getCheckTask(this.id).then((response) => {
          this.formData = response.data;
          //附件列表
          this.uncheckedInformation = response.data.uncheckInfoList;
          if (this.uncheckedInformation.length != 0) {
            for (let i = 0; i < this.uncheckedInformation.length; i++) {
              if (this.uncheckedInformation[i].taskAccessoryList.length != 0) {
                for (
                  let j = 0;
                  j < this.uncheckedInformation[i].taskAccessoryList.length;
                  j++
                ) {
                  let queryParam = {
                    filename:
                      this.uncheckedInformation[i].taskAccessoryList[j].url,
                  };
                  downloadFile(queryParam).then((res) => {
                    let blob = new Blob([res]); // 返回的文件流数据
                    let picurl = window.URL.createObjectURL(blob); // 将他转化为路径
                    this.$set(
                      this.uncheckedInformation[i].taskAccessoryList[j],
                      "picUrl",
                      picurl
                    );
                  });
                }
              }
            }
          }
          this.drawer = true;
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../../../assets/styles/dialog.scss"; //模态框样式
@import "../../../../assets/styles/drawer.scss";

::v-deep .el-form-item {
  margin-bottom: 10px !important;
}

.oucodeList {
  ::v-deep .el-form-item {
    margin: 0 !important;
  }
}

.pageHeaderSub {
  display: flex;
  align-items: center;
  padding: 10px 0;

  .pageleft {
    vertical-align: bottom;
    margin-left: 20px;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #aeafb0;
  }
  .title {
    text-align: left;
    margin: 5px 0 5px 10px;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #5e5c5c;
  }
  .searchButton1 {
    margin-left: 20px;
    margin-top: 0;
  }
}

.enclosuresBox {
  display: flex;
  flex-wrap: wrap;
}

// 图片悬浮
.enclosures2 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 200px;
  height: 120px;
  padding-right: 50px;

  // 图片区域
  .enclosurebtn2 {
    display: flex;
    align-items: center;
    position: relative;
    justify-content: center;
    width: 100%;
    height: 80%;

    // 按钮区域
    .enclosurebtn3 {
      position: absolute;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(101, 101, 101, 0.6);
      opacity: 0;
      width: 100%;
      height: 100%;
      // 图标样式
      .enclosurebtn4 {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .enclosureDel3 {
        width: 25px;
        height: 25px;
        margin: 5px;
        background-blend-mode: lighten;
        background-size: cover;
        cursor: pointer;
      }
    }
  }

  .enclosurebtn2:hover .enclosurebtn3 {
    opacity: 1;
  }
}

//分割线
::v-deep .el-divider--horizontal {
  margin: 14px 0 !important;
}

.taskName {
  width: 80%;
}

.taskName1 {
  width: 94.5%;
}

.uncheckedInfor {
  display: flex;
  // align-items: center;
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  display: none;
}

.iconClass {
  color: #4f7ff8;
  font-size: 30px;
  position: absolute;
  top: 8px;
  margin-left: 10px;
}

.searchButton1 {
  margin-top: 21px;
  width: 60px;
  height: 30px;
  background: #598af9;
  border-radius: 4px;
  margin-right: 10px;
  font-family: Microsoft YaHei;
  letter-spacing: 2px;
  color: #fefbfb;
}

.resetButton1 {
  margin-top: 21px;
  border: 1px solid #598af9;
  border-radius: 4px;
  width: 60px;
  height: 30px;
  background: #fff;
  font-family: Microsoft YaHei;
  color: #598af9;
  letter-spacing: 2px;
}

.picPreview {
  width: 100%;
  height: 100%;
}
.descriptionsContainer1 {
  padding: 15px 30px;
}
</style>
